#include<iostream>
using namespace std;
template<class K,class V>
struct BSTNode
{
	K _key;
	V _value;
	BSTNode<K>* _right;
	BSTNode<K>* _left;
	BSTNode(const K& key,const V& value)
		:_key(key)
		,_value(value)
		, _right(nullptr)
		, _left(nullptr)
	{
		
	}
};
template<class K,class V>
class BSTree
{
	typedef BSTNode<K,V> Node;
public:
	bool Insert(const K& key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}
		cur = new Node(key);
		if (parent->_key < key)
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}
		return true;
	}
	bool Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else
				return true;
		}
		return false;
	}
	bool Erase(const K& key)
	{
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_right;
					}
					else
					{
						if (parent->_left == cur)
						{
							parent->_left = cur->_right;
						}
						else 
						{
							parent->_right = cur->_right;

						}
					}
					delete cur;
					return true;
				}
				else if (cur->_right == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_left;
					}
					else
					{
						if (parent->_left == cur)
						{
							parent->_left = cur->_left;
						}
						else 
						{
							parent->_right = cur->_left;

						}
					}
					delete cur;
					return true;
				}
				else
				{
					Node* rightMinP = cur;
					Node* rightMin = cur->_right;
					while (rightMin->_left)
					{
						rightMinP = rightMin;
						rightMin = rightMin->_left;
					}
					cur->_key = rightMin->_key;
					if (rightMinP -> _left == rightMin)
						rightMinP -> _left = rightMin-> _right;
					else 
						rightMinP -> _right= rightMin-> _right;
					delete rightMin;
					return true;
				}
			}
		}
		return false;
	}
private:
	Node* _root = nullptr;
};
int main()
{
	BSTree<int> b;
	b.Insert(3);
	b.Insert(2);
	b.Insert(4);
	b.Insert(5);
	b.Insert(6);
	b.Insert(7);
	b.Find(2);
	b.Erase(4);
	return 0;
}